package com.admin.boot.common.utils;

import com.admin.boot.modules.online.service.impl.OnlineTableServiceImpl;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.Map;

/**
 * @version v3.0
 * @Description: TODO
 * @author: jeecg-boot
 * @date: 2024-01-12
 */
public class CodeGenerateUtil {


    public static void codeGenerate(String fileName, Map<String,Object> dataModel,String templateName)   {

        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter=null;
        try {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            URL resource = CodeGenerateUtil.class.getClassLoader().getResource("");
            File template = new File(resource.getFile() + "code-template");
            configuration.setDirectoryForTemplateLoading(template);
            fileWriter = new FileWriter(fileName);
            bufferedWriter = new BufferedWriter(fileWriter);
            configuration.getTemplate(templateName).process(dataModel,bufferedWriter);
            bufferedWriter.flush();
            fileWriter.close();
        } catch (Exception e) {
            if (bufferedWriter!=null){
                try {
                    bufferedWriter.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            if (fileWriter!=null){
                try {
                    fileWriter.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            throw new RuntimeException(e);
        }
    }

}
